<template>
  <div>
    <div class="mb-3">
      <!-- <el-form-item class="float-right">
        <el-button icon="el-icon-upload"
                   @click="importVisible = true">导入保单</el-button>
      </el-form-item> -->

      <el-button type="primary" @click="dialogImportVisible = true">
        <i class="fa fa-fw fa-upload"></i>
        导入保单信息
      </el-button>
    </div>

    <c-table border v-loading="loading" :columns="tableColumns" :data="tableData"></c-table>

    <div class="query-pagination">
      <div></div>
      <el-pagination
        layout="total, prev, pager, next, jumper"
        :current-page.sync="params.index"
        :page-size="params.size"
        :total="totalCount"
        @current-change="getData"
      ></el-pagination>
    </div>

    <c-form-dialog
      ref="form"
      :visible.sync="formVisible"
      :form-items="formItems"
      :form-data="formData"
      :table-name="tableName"
      :table-id="tableId"
      :service="serviceName"
      @success="getData"
    ></c-form-dialog>

    <import-excel
      :visible.sync="dialogImportVisible"
      title="导入保单信息"
      :post-api="postUrl"
      excel-template="/static/files/保单导入模板.xlsx"
      @success="handleImportSucess"
    ></import-excel>
  </div>
</template>
<script>
import { mapGetters } from 'vuex'
import { phoneValidator, idCardValidator, registerNoValidator } from '@/common/plugins/validator'
import { enumCertifyType } from '@/credit/plugins/enumInsur'
import SelectInsuranceClass from '@/credit/components/select/SelectInsuranceClass'
import SelectInsuranceOrg from '@/credit/components/select/SelectInsuranceOrg'
import ImportExcel from '@/components/ImportExcel'

export default {
  components: {
    ImportExcel,
  },
  props: {},
  data() {
    return {
      dialogImportVisible: false,
      postUrl: '',
      loading: false,
      params: {
        index: 1,
        size: 15,
        'customer_related_id.eq': '',
      },
      serviceName: 'credit',
      tableName: 'datum_customer_insurance_order',
      tableData: [],
      totalCount: 0,
      tableColumns: [
        { attrs: { label: '保单号', prop: 'insurance_order_no', minWidth: '100px' } },
        { attrs: { label: '险种', prop: 'insurance_class_name' } },
        { attrs: { label: '投保人', prop: 'ins_person' } },
        { attrs: { label: '被保人', prop: 'insured_person' } },
        { attrs: { label: '联系电话', prop: 'mobile_no', minWidth: '100px' } },
        { attrs: { label: '规模(数量)', prop: 'scale' } },
        {
          attrs: { label: '起保时间', prop: 'start_time', minWidth: '100px' },
          process: v => this.$utils.dateFormat(v, 'yyyy.MM.dd'),
        },
        {
          attrs: { label: '终保时间', prop: 'end_time', minWidth: '100px' },
          process: v => this.$utils.dateFormat(v, 'yyyy.MM.dd'),
        },
        { attrs: { label: '保险机构', prop: 'agency_name' } },
        { attrs: { label: '保费(元)', prop: 'ins_fee' } },
        { attrs: { label: '保额(万元)', prop: 'ins_funds' } },
        { attrs: { label: '自缴额(元)', prop: 'self_fee' } },
        {
          attrs: { label: '操作', align: 'center', minWidth: '100px' },
          operations: [
            { content: '编辑', icon: 'fa fa-edit', event: this.handleEdit },
            {
              content: '删除',
              icon: 'fa fa-trash',
              attrs: { class: 'text-danger py-0 px-2' },
              event: this.handleDelete,
            },
          ],
        },
      ],

      //
      tableId: '',
      formPrimaryKey: 'insurance_order_id',
      formVisible: false,
      formData: {},
      formItems: [
        {
          tag: 'input',
          itemAttrs: {
            label: '保单号',
            rules: [{ required: true, message: '请输入保单号', trigger: 'blur' }],
          },
          attrs: { key: 'insurance_order_no', value: '', placeholder: '请输入保单号' },
        },
        {
          tag: SelectInsuranceOrg,
          itemAttrs: {
            label: '保险机构',
            rules: [{ required: true, message: '请选择保险公司', trigger: 'blur' }],
          },
          attrs: {
            key: 'agency_id',
            value: '',
            placeholder: '请选择保险公司',
            class: 'form-control-ml',
          },
          listeners: {
            select: (v, n) => {
              this.$refs.form.setAttrs('agency_name', { value: n.agency_name || '' })
              this.$refs.form.setAttrs('insurance_class_id', { value: '', clientId: v })
              this.$refs.form.setAttrs('insurance_class_name', { value: '' })
            },
          },
        },
        {
          tag: 'input',
          itemAttrs: { label: '保险公司名称' },
          attrs: { key: 'agency_name', value: '' },
          ifShow: false,
        },
        {
          tag: SelectInsuranceClass,
          itemAttrs: {
            label: '险种',
            rules: [{ required: true, message: '请选择险种', trigger: 'blur' }],
          },
          attrs: {
            key: 'insurance_class_id',
            value: '',
            placeholder: '请选择险种',
            class: 'form-control-ml',
          },
          listeners: {
            select: (v, n) =>
              this.$refs.form.setAttrs('insurance_class_name', { value: n.ind_name || '' }),
          },
        },
        {
          tag: 'input',
          itemAttrs: { label: '险种名称' },
          attrs: { key: 'insurance_class_name', value: '' },
          ifShow: false,
        },
        {
          tag: 'input',
          itemAttrs: {
            label: '投保人',
            rules: [{ required: true, message: '请输入投保人', trigger: 'blur' }],
          },
          attrs: { key: 'ins_person', value: '', placeholder: '请输入投保人' },
        },
        {
          tag: 'radio-group',
          itemAttrs: {
            label: '证件类型',
            rules: [{ required: true, message: '请选择证件类型', trigger: 'change' }],
          },
          attrs: {
            key: 'certify_type',
            value: '1',
            options: enumCertifyType,
          },
        },
        {
          tag: 'input',
          itemAttrs: {
            label: '身份证号',
            rules: [
              { required: true, message: '请输入身份证号', trigger: 'blur' },
              { validator: idCardValidator, message: '请输入正确的身份证号', trigger: 'blur' },
            ],
          },
          attrs: { key: 'certify_no', value: '', placeholder: '请输入身份证号' },
          getItemAttrs: model => {
            return model.certify_type === '1'
              ? {
                  label: '身份证号',
                  rules: [
                    { required: true, message: '请输入身份证号', trigger: 'blur' },
                    {
                      validator: idCardValidator,
                      message: '请输入正确的身份证号',
                      trigger: 'blur',
                    },
                  ],
                }
              : {
                  label: '统一信用代码',
                  rules: [
                    { required: true, message: '请输入统一信用代码', trigger: 'blur' },
                    {
                      validator: registerNoValidator,
                      message: '请输入正确的统一信用代码',
                      trigger: 'blur',
                    },
                  ],
                }
          },
          getAttrs: model => {
            return model.certify_type === '1'
              ? { placeholder: '请输入身份证号' }
              : { placeholder: '请输入统一信用代码' }
          },
        },
        {
          tag: 'input',
          itemAttrs: {
            label: '被保人',
            rules: [{ required: true, message: '请输入被保人', trigger: 'blur' }],
          },
          attrs: { key: 'insured_person', value: '', placeholder: '请输入被保人' },
        },
        {
          tag: 'input',
          itemAttrs: {
            label: '联系电话',
            rules: [
              { validator: phoneValidator, message: '请输入正确的手机号码', trigger: 'blur' },
            ],
          },
          attrs: { key: 'mobile_no', value: '', placeholder: '请输入联系电话' },
        },
        {
          tag: 'number',
          itemAttrs: { label: '规模(数量)' },
          attrs: { key: 'scale', value: '', class: 'form-control-sl' },
        },
        {
          tag: 'date',
          itemAttrs: { label: '起保时间' },
          attrs: {
            key: 'start_time',
            value: '',
            placeholder: '选择起保时间',
            valueFormat: 'yyyy-MM-dd',
            class: 'form-control-sl',
          },
        },
        {
          tag: 'date',
          itemAttrs: { label: '终保时间' },
          attrs: {
            key: 'end_time',
            value: '',
            placeholder: '选择终保时间',
            valueFormat: 'yyyy-MM-dd',
            class: 'form-control-sl',
          },
        },
        {
          tag: 'number',
          itemAttrs: { label: '保费' },
          attrs: { key: 'ins_fee', value: '', class: 'form-control-sl' },
        },
        {
          tag: 'number',
          itemAttrs: { label: '保额' },
          attrs: { key: 'ins_funds', value: '', class: 'form-control-sl' },
        },
        {
          tag: 'number',
          itemAttrs: { label: '自缴额' },
          attrs: { key: 'self_fee', value: '', class: 'form-control-sl' },
        },
        {
          tag: 'input',
          itemAttrs: { label: '关联id' },
          attrs: { key: 'customer_related_id', value: '' },
          ifShow: false,
          getValue: () => this.id,
        },
      ],

      // 导入
      importVisible: false,
      importUrl: '',

      id: '',
    }
  },
  computed: {
    ...mapGetters(['clientId']),
  },
  watch: {},
  created() {
    this.id = this.$route.query.id || sessionStorage.getItem('customer_related_id')

    this.postUrl =
      '/api/credit/import/?importKey=datum_customer_insurance_order_template&where=' +
      encodeURIComponent(
        '"datum_customer_insurance_order.service_id".eq(' + this.$store.getters.org.clientId + ')'
      ) +
      encodeURIComponent('&"datum_customer_insurance_order.customer_related_id".eq(relatedId)')

    this.params['customer_related_id.eq'] = this.id
    this.getData()
  },
  mounted() {},
  methods: {
    async getData() {
      this.loading = true
      const [res] = await this.$utils.promise(
        this.$api.getData(this.serviceName, this.tableName, this.params, { create_time: 'desc' })
      )
      this.loading = false
      this.tableData = (res && res.data && res.data.data) || []
      this.totalCount = (res && res.data && res.data.totalCount) || 0
    },

    handleEdit(row) {
      this.tableId = (row && row[this.formPrimaryKey]) || ''
      this.formData = row || {}
      if (row) {
        this.$refs.form.setAttrs('insurance_class_id', { clientId: row.agency_id })
      }
      this.formVisible = true
    },

    handleDelete(row) {
      this.$msgbox({
        title: '提示',
        message: `确定删除保单：${row.insurance_order_no}?`,
        showCancelButton: true,
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        beforeClose: async (action, instance, done) => {
          if (action === 'confirm') {
            instance.confirmButtonText = '删除中...'
            instance.confirmButtonLoading = true
            const [res, err] = await this.$utils.promise(
              this.$api.deleteData(this.serviceName, this.tableName, row[this.formPrimaryKey])
            )
            instance.confirmButtonLoading = false
            instance.confirmButtonText = '确定'

            if (res) {
              this.$message.success('删除成功！')
              this.getData()
            } else {
              this.$message.error(`删除失败！${err.status}`)
            }

            done()
          } else {
            done()
          }
        },
      }).catch(() => {})
    },

    // 导入
    handleImportSucess() {
      this.getData()
      this.dialogImportVisible = false
    },
  },
}
</script>
<style lang="scss" scoped></style>
